const pool = require("./db.js");

// 创建新订单
async function createBookingOrder(order) {
  const { customerId, roomId, startTime, endTime, participantNum, orderStatus, paymentTime } = order;
  const [result] = await pool.execute(
    'INSERT INTO booking_order (customer_id, room_id, start_time, end_time, participant_num, order_status, payment_time) VALUES (?, ?, ?, ?, ?, ?, ?)',
    [customerId, roomId, startTime, endTime, participantNum, orderStatus, paymentTime]
  );
  return result.insertId;
}

// 根据用户ID获取订单列表
async function getOrdersByCustomerId(customerId) {
  const [rows] = await pool.execute(
    `SELECT bo.*, mr.room_name, mr.room_type 
     FROM booking_order bo 
     JOIN meeting_room mr ON bo.room_id = mr.id 
     WHERE bo.customer_id = ?`,
    [customerId]
  );
  return rows;
}

// 根据订单ID获取订单详情
async function getOrderById(orderId) {
  const [rows] = await pool.execute(
    `SELECT bo.*, mr.*, u.username AS customerName 
     FROM booking_order bo 
     JOIN meeting_room mr ON bo.room_id = mr.id 
     JOIN user u ON bo.customer_id = u.id 
     WHERE bo.id = ?`,
    [orderId]
  );
  return rows[0];
}

// 更新订单状态
async function updateOrderStatus(orderId, status) {
  const [result] = await pool.execute(
    'UPDATE booking_order SET order_status = ? WHERE id = ?',
    [status, orderId]
  );
  return result.affectedRows > 0;
}

// 更新订单状态为“预定”并记录支付时间
async function updateOrderToPaid(orderId) {
  const now = new Date();
  const [result] = await pool.execute(
    'UPDATE booking_order SET order_status = ?, payment_time = ? WHERE id = ?',
    ['预定', now, orderId]
  );
  return result.affectedRows > 0;
}

// 取消订单并释放会议室
async function cancelBookingOrder(orderId) {
  const [result] = await pool.execute(
    'UPDATE booking_order SET order_status = ? WHERE id = ?', 
    ['已取消', orderId]
  );

  if (result.affectedRows > 0) {
    // 获取该订单关联的会议室ID
    const [rows] = await pool.execute(
      'SELECT room_id FROM booking_order WHERE id = ?', 
      [orderId]
    );

    if (rows.length > 0) {
      const roomId = rows[0].room_id;
      // 更新会议室状态为“空闲”
      await pool.execute(
        'UPDATE meeting_room SET status = ? WHERE id = ?', 
        ['空闲', roomId]
      );
    }
  }

  return result.affectedRows > 0;
}

module.exports = {
  createBookingOrder,
  getOrdersByCustomerId,
  getOrderById,
  updateOrderStatus,
  updateOrderToPaid,
  cancelBookingOrder
};